package MetaLiteEngine;

import com.sun.net.httpserver.HttpExchange;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.HashMap;
import java.util.Map;

public class InsertObject {
    public InsertObject(String code , MetaLiteEngine metaLiteEngine) throws Exception {
        String db_data = code.substring("insert object to ".length()).trim();
        String db = db_data.substring(0,db_data.indexOf(".")).trim();
        String data = db_data.substring(db_data.indexOf(".")+1).trim();

        HashMap<String , Object> hashMap = new HashMap<>();
        Map<String , Object> objectHashMap = metaLiteEngine.readHashMapFromFile(metaLiteEngine.select_dir+"/"+db+".mdb");
        if (objectHashMap.containsKey(data)) {
            throw new Exception("the data was exists");
        }
        hashMap.put(data , getBodyAsByteArray(metaLiteEngine.httpExchange));
        metaLiteEngine.IsObj = true;
        objectHashMap.putAll(hashMap);
        metaLiteEngine.writeHashMapToFile(objectHashMap , metaLiteEngine.select_dir+"/"+db+".mdb");
        metaLiteEngine.RunMessage = "insert data successful";
    }

    public static byte[] getBodyAsByteArray(HttpExchange exchange) throws IOException {
        InputStream is = exchange.getRequestBody();
        ReadableByteChannel channel = Channels.newChannel(is);
        ByteBuffer buffer = ByteBuffer.allocate(1024); // 可以调整缓冲区大小
        int bytesRead;
        int totalBytesRead = 0;

        // 循环读取直到没有更多数据
        while ((bytesRead = channel.read(buffer)) != -1) {
            totalBytesRead += bytesRead;
            buffer.clear(); // 清除缓冲区，准备下一次读取
        }
        return buffer.array();
    }
}
